package com.galaxy.device.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.galaxy.common.core.exception.ServiceException;
import com.galaxy.common.core.utils.MapstructUtils;
import com.galaxy.common.core.utils.StringUtils;
import com.galaxy.common.mybatis.core.page.PageQuery;
import com.galaxy.common.mybatis.core.page.TableDataInfo;
import com.galaxy.device.chlients.RabbitMQClient;
import com.galaxy.device.domain.CheckStock;
import com.galaxy.device.domain.DeviceChannel;
import com.galaxy.device.domain.DeviceStock;
import com.galaxy.device.domain.bo.DeviceStockBo;
import com.galaxy.device.domain.bo.OrderBo;
import com.galaxy.device.domain.vo.DeviceStockVo;
import com.galaxy.device.mapper.DeviceChannelMapper;
import com.galaxy.device.mapper.DeviceStockMapper;
import com.galaxy.device.service.IDeviceStockService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 设备库存Service业务层处理
 */
@RequiredArgsConstructor
@Service
public class DeviceStockServiceImpl implements IDeviceStockService {

    private final DeviceStockMapper baseMapper;

    private final DeviceChannelMapper channelMapper;

    @Autowired
    private RabbitMQClient rabbitMQClient;


    @DS("slave")
    @Override
    public TableDataInfo<DeviceStockVo> queryPageList(DeviceStockBo bo, PageQuery pageQuery) {
        DeviceStock query = MapstructUtils.convert(bo, DeviceStock.class);
        IPage<DeviceStockVo> result = baseMapper.selectVoPage(pageQuery.build(), query);
        return TableDataInfo.build(result);
    }

    @DS("slave")
    @Override
    public DeviceStockVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }


    @Override
    public Boolean insertByBo(DeviceStockBo bo) {
        DeviceStock add = MapstructUtils.convert(bo, DeviceStock.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(DeviceStockBo bo) {
        DeviceStock update = MapstructUtils.convert(bo, DeviceStock.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(List<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO: 做一些业务上的校验,判断是否允许删除
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<DeviceStockVo> queryAlertList(DeviceStockBo bo, PageQuery pageQuery) {
        DeviceStock query = MapstructUtils.convert(bo, DeviceStock.class);
        // 设置状态为缺货
        query.setStatus(0);
        IPage<DeviceStockVo> result = baseMapper.selectVoPage(pageQuery.build(), query);
        return TableDataInfo.build(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchUpdate(List<DeviceStockBo> boList) {
        List<DeviceStock> updateList = MapstructUtils.convert(boList, DeviceStock.class);
        for (DeviceStock stock : updateList) {
            validEntityBeforeSave(stock);
            baseMapper.updateById(stock);
        }
        return true;
    }

    @Override
    public List<DeviceStockVo> getDevice(Long productId) {

        return baseMapper.selectVoList(new LambdaQueryWrapper<DeviceStock>()
            .eq(DeviceStock::getProductId, productId)
            .eq(DeviceStock::getStatus, 1)
            .gt(DeviceStock::getStockQuantity, 0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean checkStock(List<CheckStock> checkStock, OrderBo orderBo) {
        for (CheckStock stock : checkStock) {
            DeviceStock deviceStockList = baseMapper.selectOne(new LambdaQueryWrapper<DeviceStock>()
                .eq(DeviceStock::getDeviceId, stock.getDeviceId())
                .eq(DeviceStock::getChannelId, stock.getChannelId())
                .eq(DeviceStock::getProductId, stock.getProductId()));
            if(deviceStockList != null){
                if(deviceStockList.getStockQuantity() >= stock.getStock()){
                    deviceStockList.setStockQuantity(deviceStockList.getStockQuantity() - stock.getStock());
                    baseMapper.updateById(deviceStockList);

                }else {
                    throw new ServiceException("库存不足");
                }
            }else {
                throw new ServiceException("无此库存");
            }
        }
        rabbitMQClient.sendTimoutMessage(JSON.toJSONString(orderBo),900000);

        return rabbitMQClient.sendMessage(JSON.toJSONString(orderBo));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStock(List<CheckStock> checkStockList) {
        for(CheckStock checkStock : checkStockList){
            DeviceChannel deviceChannel = channelMapper.selectOne(new LambdaQueryWrapper<DeviceChannel>()
                .eq(DeviceChannel::getDeviceId, checkStock.getDeviceId())
                .eq(DeviceChannel::getChannelNo, checkStock.getChannelId())
            .eq(DeviceChannel::getStatus,1));
            DeviceStock deviceStock = baseMapper.selectOne(new LambdaQueryWrapper<DeviceStock>()
                .eq(DeviceStock::getDeviceId, checkStock.getDeviceId())
                .eq(DeviceStock::getChannelId, deviceChannel.getId())
                .eq(DeviceStock::getProductId, checkStock.getProductId()));
                deviceStock.setStockQuantity(deviceStock.getStockQuantity() + checkStock.getStock());
            baseMapper.updateById(deviceStock);
        }

        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DeviceStock entity) {
        // TODO: 做一些实体的数据校验,如唯一约束
        if (entity.getStockQuantity() > entity.getMaxQuantity()) {
            entity.setStatus(2); // 超量
        } else if (entity.getStockQuantity() <= entity.getMinQuantity()) {
            entity.setStatus(0); // 缺货
        } else {
            entity.setStatus(1); // 正常
        }
    }
}
